<template>
  <div class="rent-record">
    <div class="page-header">
      <h2>租赁记录</h2>
      <el-button type="success" icon="el-icon-download" @click="handleExport">导出记录</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-box">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="房源标题">
          <el-input v-model="searchForm.title" placeholder="请输入房源标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="租客姓名">
          <el-input v-model="searchForm.tenantName" placeholder="请输入租客姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="租赁中" value="1"></el-option>
            <el-option label="已结束" value="2"></el-option>
            <el-option label="已终止" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="summary-box">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="summary-item">
            <div class="summary-label">总租赁次数</div>
            <div class="summary-value">{{ summary.totalCount }}次</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="summary-item">
            <div class="summary-label">总收入</div>
            <div class="summary-value">¥{{ summary.totalIncome }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="summary-item">
            <div class="summary-label">平均租期</div>
            <div class="summary-value">{{ summary.avgDuration }}个月</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <el-table :data="tableData" border stripe v-loading="loading">
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
      <el-table-column prop="houseTitle" label="房源标题" min-width="200"></el-table-column>
      <el-table-column prop="address" label="地址" min-width="180"></el-table-column>
      <el-table-column prop="tenantName" label="租客姓名" width="100"></el-table-column>
      <el-table-column prop="tenantPhone" label="联系电话" width="120"></el-table-column>
      <el-table-column prop="price" label="月租金" width="100" align="right">
        <template slot-scope="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="rentStartTime" label="起租日期" width="110"></el-table-column>
      <el-table-column prop="rentEndTime" label="结束日期" width="110"></el-table-column>
      <el-table-column prop="duration" label="租期" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.duration }}个月
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额" width="100" align="right">
        <template slot-scope="scope">
          ¥{{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">租赁中</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="info">已结束</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="warning">已终止</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleContract(scope.row)">合同</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-box">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 详情对话框 -->
    <el-dialog title="租赁记录详情" :visible.sync="dialogVisible" width="50%">
      <el-descriptions :column="2" border v-if="currentRecord">
        <el-descriptions-item label="房源标题">{{ currentRecord.houseTitle }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ currentRecord.address }}</el-descriptions-item>
        <el-descriptions-item label="租客姓名">{{ currentRecord.tenantName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentRecord.tenantPhone }}</el-descriptions-item>
        <el-descriptions-item label="月租金">¥{{ currentRecord.price }}</el-descriptions-item>
        <el-descriptions-item label="押金">¥{{ currentRecord.deposit }}</el-descriptions-item>
        <el-descriptions-item label="起租日期">{{ currentRecord.rentStartTime }}</el-descriptions-item>
        <el-descriptions-item label="结束日期">{{ currentRecord.rentEndTime }}</el-descriptions-item>
        <el-descriptions-item label="租期">{{ currentRecord.duration }}个月</el-descriptions-item>
        <el-descriptions-item label="总金额">¥{{ currentRecord.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="currentRecord.status === 1" type="success">租赁中</el-tag>
          <el-tag v-else-if="currentRecord.status === 2" type="info">已结束</el-tag>
          <el-tag v-else-if="currentRecord.status === 3" type="warning">已终止</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentRecord.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RentRecord',
  data() {
    return {
      loading: false,
      searchForm: {
        title: '',
        tenantName: '',
        status: ''
      },
      dateRange: [],
      summary: {
        totalCount: 0,
        totalIncome: 0,
        avgDuration: 0
      },
      tableData: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      currentRecord: null
    }
  },
  created() {
    this.loadSummary()
    this.loadData()
  },
  methods: {
    loadSummary() {
      // 获取统计数据
      const userInfo = localStorage.getItem('userInfo')
      if (!userInfo) return

      const user = JSON.parse(userInfo)
      // 如果是房东，统计房东的租赁记录
      if (user.role === 1) {
        this.$network.getLandlordApplies({ pageNo: 1, pageSize: 999, status: 1 }).then(res => {
          if (res.data.code === 200) {
            const applies = res.data.data.list || []
            this.summary.totalCount = applies.length
            this.summary.totalIncome = applies.reduce((sum, item) => sum + (item.price || 0), 0)
            const firstPrice = (applies[0] && applies[0].price) || 1
            this.summary.avgDuration = applies.length > 0 ? Math.round((this.summary.totalIncome / applies.length / firstPrice) * 10) / 10 : 0
          }
        }).catch(error => {
          console.error('加载统计数据失败:', error)
        })
      } else {
        // 租客统计
        this.$network.getMyApplies({ pageNo: 1, pageSize: 999, status: 1 }).then(res => {
          if (res.data.code === 200) {
            const applies = res.data.data.list || []
            this.summary.totalCount = applies.length
            this.summary.totalIncome = applies.reduce((sum, item) => sum + (item.price || 0), 0)
          }
        }).catch(error => {
          console.error('加载统计数据失败:', error)
        })
      }
    },
    loadData() {
      this.loading = true
      const userInfo = localStorage.getItem('userInfo')
      if (!userInfo) {
        this.$message.error('请先登录')
        this.$router.push('/login')
        return
      }

      const user = JSON.parse(userInfo)
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        keyword: this.searchForm.title || this.searchForm.tenantName || undefined,
        status: this.searchForm.status === '' ? undefined : parseInt(this.searchForm.status),
        startTime: this.dateRange && this.dateRange.length > 0 ? this.dateRange[0] + ' 00:00:00' : undefined,
        endTime: this.dateRange && this.dateRange.length > 0 ? this.dateRange[1] + ' 23:59:59' : undefined
      }

      // 根据角色调用不同API
      const apiMethod = user.role === 1 ? this.$network.getLandlordApplies : this.$network.getMyApplies

      apiMethod(params).then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data.list || []
          // 处理数据，计算租期和总金额
          this.tableData.forEach(record => {
            // 计算租期（月数）
            if (record.rentStartTime && record.rentEndTime) {
              const start = new Date(record.rentStartTime)
              const end = new Date(record.rentEndTime)
              record.duration = Math.round((end - start) / (1000 * 60 * 60 * 24 * 30))
            } else {
              record.duration = 0
            }
            // 计算总金额
            record.totalAmount = (record.price || 0) * (record.duration || 0)
            // 映射字段
            record.houseTitle = record.houseTitle || '未知'
            record.address = record.houseAddress || '未知'
            record.tenantName = record.userName || record.tenantName || '未知'
            record.tenantPhone = record.contactPhone || record.tenantPhone || '未知'
          })
          this.total = res.data.data.total || 0
        } else {
          this.$message.error(res.data.message || '获取租赁记录失败')
        }
      }).catch(error => {
        console.error('获取租赁记录失败:', error)
        this.$message.error('获取租赁记录失败')
      }).finally(() => {
        this.loading = false
      })
    },
    handleSearch() {
      this.pageNo = 1
      this.loadData()
    },
    handleReset() {
      this.searchForm = {
        title: '',
        tenantName: '',
        status: ''
      }
      this.dateRange = []
      this.pageNo = 1
      this.loadData()
    },
    handleExport() {
      this.$message.success('导出功能开发中...')
    },
    handleView(row) {
      this.currentRecord = row
      this.dialogVisible = true
    },
    handleContract(row) {
      this.$message.info('查看合同功能开发中...')
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.loadData()
    }
  }
}
</script>

<style scoped>
.rent-record {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-box {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.summary-box {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.summary-item {
  text-align: center;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  color: #fff;
}

.summary-label {
  font-size: 14px;
  margin-bottom: 10px;
  opacity: 0.9;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
}

.pagination-box {
  margin-top: 20px;
  text-align: right;
}
</style>

